package com.ljs.liojbackendjudgeservice.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.ljs.libackendmodel.model.codesandbox.QuestionJudgeInfo;
import com.ljs.libackendmodel.model.dto.question.QuestionJudgeCase;
import com.ljs.libackendmodel.model.dto.question.QuestionJudgeConfig;
import com.ljs.libackendmodel.model.entity.Question;
import com.ljs.libackendmodel.model.enums.JudgeInfoMessageEnum;

import java.util.List;

public class DefaultJudgeStrategy implements JudgeStrategy {
    @Override
    public QuestionJudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.WAiTING;
        //先判断沙箱执行的结果输出数量是否和预期输出数量相等
        QuestionJudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        List<QuestionJudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();


        long memory = judgeInfo.getMemory();
        long time = judgeInfo.getTime();
        QuestionJudgeInfo judgeInfoResponse=new QuestionJudgeInfo();
        judgeInfoResponse.setTime(time);
        judgeInfoResponse.setMemory(memory);

        if(inputList!=outputList){
            judgeInfoMessageEnum=JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;

        }
        //依次判断每一项输出和预期输出是否相等
        for (int i = 0; i < judgeCaseList.size(); i++) {
            QuestionJudgeCase questionJudgeCase = judgeCaseList.get(i);
            String output = questionJudgeCase.getOutput();
            if(output.equals(outputList.get(i))){
                judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResponse;
            }
        }
//        3.判题题目的限制是否符合要求


        String judgeConfigStr = question.getJudgeConfig();
        QuestionJudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, QuestionJudgeConfig.class);
        long needMemoryLimit = judgeConfig.getMemoryLimit();
        long needTimeLimit = judgeConfig.getTimeLimit();

        if(memory>needMemoryLimit){
            judgeInfoMessageEnum= JudgeInfoMessageEnum.MemoryLimitExceeded;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        if(time>needTimeLimit){
            judgeInfoMessageEnum=judgeInfoMessageEnum.TimeLimitExceeded;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }

        judgeInfoResponse.setMessage(judgeInfoMessageEnum.Accepted.getValue());
        return judgeInfoResponse;
    }
}
